import  React, { FC } from 'react'
import './EditCanvas.css'
import { Spin } from 'antd'
import { useDispatch } from 'react-redux'
import useGetComponentInfo from '../../../hooks/useGetComponentinfo.ts'
import { getComponentConfByType } from '../../../components/QuestionComponents/index.ts'
import { ComponentInfoType,changeSelectedId } from '../../../store/componentsReducer/index.ts'
import classNames from 'classnames'
import styles from './EditCanvas.module.scss'
import useBindCanvasKeyPress from '../../../hooks/useBindCanvasKeyPress.ts'

// 临时看下效果
// import QuestionTitle from '../../../components/QuestionComponents/QuestionTitle/Component.tsx'
// import QuestionInput from '../../../components/QuestionComponents/QuestionInput/Component.tsx'

type PropsType = {
    loading:boolean
}

function getComponent(componentInfo:ComponentInfoType){
    const { type,props } = componentInfo // 组件信息数组里面单个对象
    const componentConf = getComponentConfByType(type)
    if(componentConf == null) return null
    const { Component } =  componentConf

    return <Component {...props} />
}
const EditCanvas: FC<PropsType> = ({loading})=>{
    const dispatch = useDispatch()
    const { componentList,selectedId } = useGetComponentInfo()
    
    function handleClick(event: MouseEvent, id: string){
        event.stopPropagation() // 阻止冒泡到 index.tsx文件的这一行，因为它会清空 <div className="main" onClick={()=> clearSelectedId()}>
        // console.log('当前id',id)
        dispatch(changeSelectedId(id))
    }

    // 绑定快捷键
    useBindCanvasKeyPress()


    if(loading){
        return (
            <div style={{ textAlign:'center', marginTop:'24px' }}>
                <Spin />
            </div>
        )
    }
    return (
        <div className={styles.canvas}>
            {componentList.filter(v=> !v.isHidden).map(c => {
                const {fe_id,isLocked} = c

                // 拼接class name
                const wrapperDefaultClassName = styles['component-wrapper']
                const selectedClassName = styles.selected
                const lockedClassName = styles.locked
                const wrapperClassName = classNames({
                [wrapperDefaultClassName]: true,
                [selectedClassName]: fe_id === selectedId,
                // 锁定的样式
                [lockedClassName]: isLocked
                })

                return <div key={fe_id} className={wrapperClassName} onClick={(e)=>handleClick(e,fe_id)}>
                    <div className={styles.component}>
                        {getComponent(c)}
                    </div>
                </div>
            })}
            {/* <div className="cwrapper">
                <div className="component">
                    <QuestionTitle />
                </div>
            </div>
            <div className="cwrapper">
                <div className="component">
                    <QuestionInput />
                </div>
            </div> */}
        </div>
    )
}

export default EditCanvas